const  Order  = require('../collection/order')
const { removeEmptyValues,generateUUID, varifyToken} = require('../../utils/methold')
const User = require("../collection/user");
const Goods= require('../collection/goods')
const { wx} = require('./../../utils/config')
const  { wxPay, pay} = require('./../../routers/weixin/pay')
const moment = require("moment");
const consola = require('consola') //格式化打印插件 也可以不用用console
// const { createToken, varifyToken, removeEmptyValues, generateUUID } = require('../../utils/methold')



const getUserInfoByToken =  async(ctx) => {
    return new Promise(async (resolve,reject) => {
        const token = ctx.headers.authorization
        if (!token) return  reject() // 无效的token 失效
        const res = await varifyToken(token)
        // 解密token
        if(res && res.userInfo) {
            const openid = res.userInfo.openid
            const user = await User.findOne({openid})
            // 不存在用户,重新登录注册
            if (!user) {
                return  reject() //  无效的token
            }
            resolve(user)
        } else{
            return  reject() // 无效的token 失效
        }

    })

}
module.exports = {
    // orderNo: { type: String }, //订单号
    // userId: { type: String },// 下单人
    // address: { type: String },// 后货地址
    // community: {type: String }, // 小区
    // phone: { type: String },// 联系电话
    // goodsList: {
    // }, // 商品集合
    // status: {
    //     enum: [0,1,2,3,4,5,6]  // 0 待支付 1已支付 2待派送 3派送中 4已完成 5 退货中 6 已退货
    // },
    // createDate: {
    // },
    // updateDate: {
    // }
    add: async (ctx)=> {
        const  {
            contactName,
            contactCommunity,
            contactAddress,
            contactPhone,
            goodsList,
            remark,
        } = ctx.request.body
        // const token = ctx.headers.authorization
        const user = await getUserInfoByToken(ctx)
        if(!user) {
            ctx.body = {
                status: 20001 ,
                msg: '无效的token,请重新登录',
                data: null
            }
            return
        }
        const ids = goodsList.map(item => {
            return item.goodsId
        })
        let addGoods = await Goods.find({_id : {$in: ids }})
        if(addGoods.length !== addGoods.filter(item => item.status).length) {
            ctx.body = {
                status: 'error',
                msg: '部分商品信息更新了，请重新下单',
                data: null
            }
            return
        }
        let amount = addGoods.reduce((prev, cur, index, arr) =>{
            return ( prev+ (cur.price * cur.discount/10))
        },0)
        amount = amount.toFixed(2)
        const order = {
            orderNo: generateUUID(),
            userId: user.openid,
            amount: Number(amount),
            contactName,
            contactCommunity,
            contactAddress,
            contactPhone,
            goodsList,
            remark,
            status: 0, //0 待支付 1已支付  2 已过期 3待派送 4派送中 5已完成 6退货中 99已退货
            createDate: new Date(),
            endTime: moment().add(30, 'minutes').toDate()
        }

        const newOrders = new Order(order)
        const  res =  await newOrders.save()
        const data =  {
            ...res._doc
        }
        data.goodsId = res._id
        delete data._id
        const  shoppingCart = user.shoppingCart.filter(item => !ids.includes(item.goodsId))
        await User.updateOne({ openid: user.openid },{ $set:{ shoppingCart} })
        ctx.body = {
            status: 200,
            msg: '下单成功',
            data
        }
    },
    update: async (ctx) =>{
        try {
            const  {
                orderNo,
            } = ctx.request.body
            if (!orderNo) {
                ctx.body = {
                    status: 'error',
                    msg: '必要orderNo 不能为空!'
                }
            }

            let params = {
                ...ctx.request.body
            }
            delete params.orderNo
            params = removeEmptyValues(params)
            const filter = { orderNo: `${orderNo}` }
            const res = await Order.updateOne(filter,{ $set:params })
            if(res.acknowledged && res.modifiedCount) {
                ctx.body = {
                    status: 200,
                    data: {},
                    msg: '修改成功'
                }
            }else {
                ctx.body = {
                    status: 'error',
                    data: {},
                    msg: '数据异常'
                }
            }
        }
        catch(error){
            ctx.body = {
                status: 'error',
                data: {},
                msg: '修改失败'
            }
        }
    },
    getList: async (ctx) => {
        try {
            const  { pageSize, currentPage } = ctx.request.query
            let query = {
                ...ctx.request.query
            }

            delete query.pageSize
            delete query.currentPage
            query = removeEmptyValues(query)
            const list = await Order.find(query).skip(pageSize * (currentPage - 1)).limit(pageSize)
            const data = list.map((item) => {
                // 待支付 订单需要查询一下过期时间
                // maybe// 0 待支付 1已支付 2待派送 3派送中 4已完成 5 退货中 6 已退货 7 已过期
                let status = item._doc.status
                if(status === 0 && moment().isAfter(item.endTime)) {
                    Order.updateOne({ _id: item._id }, { $set: { status: 7 } })
                    status = 7
                }
                return {
                    ...item._doc,
                    status,
                    createDate:moment(item.createDate).format('YYYY-MM-DD HH:mm:ss'),
                    endTime:moment(item.endTime).format('YYYY-MM-DD HH:mm:ss'),
                }

            })
            const total = await Order.countDocuments(query);
            if (data && data.length) {
                ctx.body = {
                    status: 200,
                    data: {
                        list: data,
                        total,
                        pageSize: Number(pageSize),
                        currentPage: Number(currentPage),
                    },
                    msg: '成功'
                }
            } else {
                ctx.body = {
                    status: 200,
                    data: [],
                    msg: '成功'
                }
            }
        }
        catch(error) {
            ctx.body = {
                status: 'error',
                data: [],
                msg: '失败'
            }
        }
    },
    getUserList: async (ctx) => {
        try {
            const  { pageSize, currentPage } = ctx.request.query
            let query = {
                ...ctx.request.query
            }
            const token = ctx.headers.authorization
            const _user = await varifyToken(token)
            delete query.pageSize
            delete query.currentPage
            query = removeEmptyValues(query)
            query.userId = _user.userInfo.openid
            const list = await Order.find(query).sort({createDate: -1}).skip(pageSize * (currentPage - 1)).limit(pageSize)
            const data = list.map((item) => {
                // 待支付 订单需要查询一下过期时间
                // maybe// 0 待支付 1已支付 2待派送 3派送中 4已完成 5 退货中 6 已退货 7 已过期
                let status = item._doc.status
                if(status === 0 && moment().isAfter(item.endTime)) {
                    Order.updateOne({ _id: item._id }, { $set: { status: 7 } })
                    status = 7
                }
                return {
                    ...item._doc,
                    status,
                    createDate:moment(item.createDate).format('YYYY-MM-DD HH:mm:ss'),
                    endTime:moment(item.endTime).format('YYYY-MM-DD HH:mm:ss'),
                }

            })
            if (list) {
                ctx.body = {
                    status: 200,
                    data: data,
                    msg: '成功'
                }
            } else {
                ctx.body = {
                    status: 200,
                    data: [],
                    msg: '成功'
                }
            }
        }
        catch(error) {
            ctx.body = {
                status: 'error',
                data: [],
                msg: '失败'
            }
        }
    },
    delete: async (ctx) =>{
        try {
            const  {
                orderNo,
            } = ctx.request.query
            if (!orderNo) {
                ctx.body = {
                    status: 'error',
                    msg: '必要orderNo 不能为空!'
                }
            }
            const params = { orderNo: `${orderNo}` }
            const res = await Order.deleteOne(params)
            if (res.deletedCount) {
                ctx.body = {
                    status: 200,
                    msg: '删除成功',
                    data: {}
                }
            } else {
                ctx.body = {
                    status: 200,
                    msg: '请勿重新删除',
                    data: {}
                }
            }
        }
        catch {
            ctx.body = {
                status: 200,
                msg: '删除失败',
                data: {}
            }
        }
    },
    detail: async (ctx) => {
        try {
            const  { orderNo } = ctx.request.query
            const params = { orderNo: `${orderNo}` }
            const item = await Order.findOne(params)
            const data = {
                ...item._doc,
                createDate:moment(item.createDate).format('YYYY-MM-DD HH:mm:ss'),
                endTime:moment(item.endTime).format('YYYY-MM-DD HH:mm:ss'),
                updateDate:moment(item.updateDate).format('YYYY-MM-DD HH:mm:ss'),
            }
            if (item) {
                ctx.body = {
                    status: 200,
                    data: data,
                    msg: '成功'
                }
            } else {
                ctx.body = {
                    status: 'error',
                    data: {},
                    msg: '查询失败'
                }
            }
        }
        catch(error) {
            ctx.body = {
                status: 'error',
                data: {},
                msg: '查询失败'
            }
        }
    },
    pay: async (ctx) => {
        let {
            orderNo,
            amount,
        } = ctx.request.body
        consola.success(ctx.request.body)
        const token = ctx.headers.authorization
        if (!token) return  reject() // 无效的token 失效
        const user = await varifyToken(token)
        const params = {
            orderNo: orderNo,
            money: amount,
            userId: user.userInfo.openid
        }
        const res = await wxPay(params)
        if(res && res.status === 200) {
            ctx.body = {
                status: 200,
                data: res.data,
                msg: '微信下单成功'
            }
            return
        }
        ctx.body = {
            status: 'err',
            data: res,
            msg: '微信下单失败'
        }
    },
    complatePay: async (ctx) => {
        const {
            orderNo
        } = ctx.request.body
        await Order.updateOne({
            orderNo: orderNo
        }, {
            $set: {
                status: 1,
            }
        })
        ctx.body = {
            status: 200,
            data: {},
            msg: '支付完成'
        }
    },

    payResult: async (ctx) =>{
        try {

            // 申请的APIv3
            let key = wx.partner_key;
            let {
                ciphertext,
                associated_data,
                nonce
            } = ctx.request.boby.resource;
            // 解密回调信息
            consola.success(ciphertext,associated_data,nonce,key,'微信支付body回调')
            const result = pay.decipher_gcm(ciphertext, associated_data, nonce, key);
            consola.success(result,'微信支付回调解析')
            if (result.trade_state === 'SUCCESS') {
                await Order.updateOne({
                    orderNo: result.out_trade_no
                }, {
                    $set: {
                        status: 1,
                        // transactionId: result.transaction_id // 交易的id
                    }
                })
            } else  {
            }
            ctx.body = {
                status: 200,
                data: {},
                msg: '支付成功'
            }
        } catch (error) {
            ctx.body = {
                status: 200,
                data: {},
                msg: '支付失败'
            }
        }
    }

}